package indi.jp.project.core.util;

import indi.jp.project.core.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

public class JwtUtil {

    // 请求头
    public static final String HEADER = "Authorization";

    // 前缀
    public static final String HEADER_PREFIX = "Bearer ";

    // 密钥
    public static final String SECRET_KEY = "aKe3jfr6j0K-bKa3NrVxff51iyrF4sHqFRNunv4L3NrWkZYHO3lLcb1G6PnFH5tWKgaSQNwqOTr3h_LDHilWPd-liXT-hQSyNhPYDDOqL-mCwpbNBHhfy6J-nYRAfTTf__7R_JPmnJXg4eSx-eeWNfqfKvNyYUii6BKfhAAUr6qzvgfxTthNeRbuj6-S1tUGQQ6qKSDD7_zSUpGogmgE_CHl4PYeqaui5eoJNXrddwZfPQyVLQ4vQqeXW7rgOVxh";

    // 过期时间
    public static final long EXPIRES_IN = 259200L;

    private static Key getKey() {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] bytes = DatatypeConverter.parseBase64Binary(SECRET_KEY);
        return new SecretKeySpec(bytes, signatureAlgorithm.getJcaName());
    }

    /**
     * 创建令牌
     *
     * @param user
     * @return
     */
    public static String createToken(User user) {
        Claims claims = Jwts.claims();
        claims.put("authority", user.getAuthorities());
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(user.getUsername())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRES_IN * 1000))
                .signWith(getKey())
                .compact();
    }

    /**
     * 获取令牌内容
     *
     * @param token
     * @return
     */
    public static Claims getTokenBody(String token) {
        return Jwts.parserBuilder().setSigningKey(getKey()).build().parseClaimsJws(token).getBody();
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token
     * @return
     */
    public static String getUserName(String token) {
        return getTokenBody(token).getSubject();
    }

    /**
     * 令牌是否已过期
     *
     * @param token
     * @return
     */
    public static boolean isExpired(String token) throws ExpiredJwtException {
        return getTokenBody(token).getExpiration().before(new Date());
    }

}
